//
//  ZJOAuthWebViewController.swift
//  Webo
//
//  Created by 曾静 on 16/6/25.
//  Copyright © 2016年 qq. All rights reserved.
//

import UIKit
import SVProgressHUD
class ZJOAuthWebViewController: UIViewController {

    
    override func loadView() {
        view = webView
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.whiteColor()
      
        setNav()
    }
    
    func setNav(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelBtnClick")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFillClick")
        navigationItem.title = "OAuth登录"

    }
    
    @objc private func cancelBtnClick(){
        
        dismissViewControllerAnimated(true, completion: nil)
        print("取消")
    }

    @objc private func autoFillClick(){
        
        let jsString = "document.getElementById('userId').value='13315088145',document.getElementById('passwd').value='a06131024w'"
    
        webView.stringByEvaluatingJavaScriptFromString(jsString)

        
    }
    
    //必须是懒加载的控件
   lazy private var webView:UIWebView = {

        
        let web =  UIWebView()
        
        web.delegate = self
        
        let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(APPKEY)&redirect_uri=\(REDIRECT_URI)")
        
        let resquest = NSURLRequest(URL: url!)
        
        web.loadRequest(resquest)
        
        return web

    
    }()
}

extension ZJOAuthWebViewController: UIWebViewDelegate{
    
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        print("加载失败")
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
//        print(request)
        
        let urlString = request.URL?.absoluteString
        
        
        if let urlS = urlString where urlS.hasPrefix(REDIRECT_URI){
            
            if let q = request.URL?.query{
                
               let code = q.substringFromIndex("code=".endIndex)
                
                //调用获取AccessToken的方法,将code传进去
                getAccessToken(code)
               
                SVProgressHUD.dismiss()
                
                return false
        
            }
        }
        
        
        return true
    }
    
    
    
    func webViewDidFinishLoad(webView: UIWebView) {
        print("加载完成")
        SVProgressHUD.dismiss()
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        print("开始加载")
        SVProgressHUD.show()
    }
}
extension ZJOAuthWebViewController{
    
    //获取token
    func getAccessToken(code:String){
        
        //需要利用封装好的网络工具类
        
        ZJNetWorkTools.shareTools.getToken(code) { (response, error) -> () in
            
            
            if error != nil{
                print("网络请求失败")
                
                return
            }
           
            guard let res = response as? [String : AnyObject] else{

                return
            }
            
            
             //到这里,网络请求成功,并且返回数据不为空且可以转化为字典的类型
            
            let userAccount:ZJUserAccount = ZJUserAccount(dict: res)
            
            self.getUserInfo(userAccount)
            
            
            
        }
        
    }
    //获取用户信息
    func getUserInfo(userAccount:ZJUserAccount){
        
        ZJNetWorkTools.shareTools.getUserAccount(userAccount) { (response, error) -> () in
            
            if error != nil{
                
                print(error)
                
                return
            }
            
            guard let res = response as? [String : AnyObject] else{
                
                return
            }

            userAccount.avatar_large = res["avatar_large"] as?String
            
            userAccount.screen_name = res["screen_name"]as?String
            
            ZJUserInfoTools.shareUserInfo.saveUserInfo(userAccount)
            
//            print(ZJUserInfoTools.shareUserInfo.isLogin)
            
            self.dismissViewControllerAnimated(false, completion: { () -> Void in
                //获取用户信息成功,可以跳转到欢迎界面
                
                NSNotificationCenter.defaultCenter().postNotificationName(switchVc, object: nil)
            })
            
        }
        
    }
    

}